#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import sys

from common import cleaner
from common.common import exter_attack
from common.const import ExecuteResultEnum, SysData
from common.logger import Logger
from common.parse_parafile import ParamFileUtil
from db2.backup.util.dpf_backup_util import DpfBackupUtil
from db2.comm.util.common_util import Db2CommonUtil
from db2.backup.delete_copy import DeleteCopy

LOGGER = Logger().get_logger(filename="db2.log")


@exter_attack
def distribute_task(task_name, pid, job_id, param_dict, sub_job_id=None):
    delete_copies_obj = DeleteCopy(task_name, pid, job_id, param_dict, sub_job_id)
    cmd_dict = {
        "DeleteCopy": {
            "exec_job_func": delete_copies_obj.delete_copies,
            "output_result_func": delete_copies_obj.output_action_result,
        },
        "DeleteCopyProgress": {
            "exec_job_func": delete_copies_obj.delete_progress,
            "output_result_func": delete_copies_obj.output_action_result
        }
    }

    job_func_dict = cmd_dict.get(task_name, None)
    if not job_func_dict:
        LOGGER.error(f"Unsupported job action: {task_name}, pid: {pid}, job_id: {job_id}")
        err_msg = f"Unsupported job action: {task_name}."
        Db2CommonUtil.record_task_result(pid=pid, err_msg=err_msg, code=ExecuteResultEnum.INTERNAL_ERROR.value)
        return

    action_ret = job_func_dict["exec_job_func"]()
    if job_func_dict.get("output_result_func"):
        job_func_dict["output_result_func"](action_ret)


@exter_attack
def main():
    args = sys.argv[1:]
    # 参数个数为1
    if len(args) not in (2, 3, 4):
        LOGGER.error(f"Param number error! Arguments: {args}")
        return ExecuteResultEnum.INTERNAL_ERROR

    task_name, pid = args[0], args[1]
    job_id = args[2] if len(args) >= 3 else ""
    input_sub_job_id = args[3] if len(args) == 4 else ""
    LOGGER.info(f"Start exec task {task_name}. pid: {pid}, job_id: {job_id}, "
                f"sub_job_id: {input_sub_job_id}.")
    try:
        param_dict = ParamFileUtil.parse_param_file(pid)
    except Exception:
        LOGGER.exception(f"Parse param file failed, task name: {task_name}, pid: {pid}, job_id: {job_id}.")
        err_msg = "Parse parameter file failed."
        DpfBackupUtil.record_task_result(pid, err_msg, code=ExecuteResultEnum.INTERNAL_ERROR.value)
        return ExecuteResultEnum.INTERNAL_ERROR

    try:
        distribute_task(task_name, pid, job_id, param_dict, sub_job_id=input_sub_job_id)
    except Exception:
        LOGGER.exception(f"Distribute DB2 database backup task failed. Task Name: {task_name},"\
                        f"Pid: {pid}, Job ID: {job_id}, Sub Job ID: {input_sub_job_id}.")
        return ExecuteResultEnum.INTERNAL_ERROR
    LOGGER.info(f"Execute task {task_name} success. Pid: {pid}, Job ID: {job_id}, "
                f"Sub Job ID: {input_sub_job_id}.")
    return ExecuteResultEnum.SUCCESS


if __name__ == '__main__':
    try:
        sys.exit(main())
    finally:
        cleaner.clear(SysData.SYS_STDIN)
        LOGGER.debug('Clear environment variables successfully.')
